/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package formularios;

import Clases.AnchoColumna;
import Clases.AutoCompleteCombo;
import Clases.ComboBox;
import Clases.ModeloTabla;
import Clases.Tools;
import Clases.Transacciones;
import de.javasoft.swing.JYTable;
import de.javasoft.swing.JYTableHeader;
import de.javasoft.swing.JYTableScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.JTextComponent;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Jrg
 */
public class EliminarInscripcion extends javax.swing.JInternalFrame {

    public static int IdMenu=11;
    JTable _tabla;
    ModeloTabla _modeloTabla;
    double _total;
    int _IdInscripcion=0;
    /**
     * Creates new form inscripciones
     */
    public EliminarInscripcion() 
    {
        initComponents();
        CrearModeloTabla();
        CargarTabla();
    }
    
   
    private void CrearModeloTabla()
    {
        try
        {
            /*columnas que no son editables*/
            Hashtable colReadOnly= new Hashtable();
            colReadOnly.clear();
            colReadOnly.put(0, 0); //IdInscripcion
            colReadOnly.put(1, 300); //Alumno
            colReadOnly.put(2, 200); //Grado
            colReadOnly.put(3, 100); //Saldo
            String[] columnNames = {"IdInscripcion","Alumno", "Grado","Monto"};
            final Class<?>[] columnClasses = {Integer.class,String.class, String.class, Double.class}; 
            _modeloTabla = new ModeloTabla(colReadOnly);
            _modeloTabla.setColumnIdentifiers(columnNames);
            _modeloTabla.RemoveAllRows();
            _tabla = new JTable(_modeloTabla)
            {
                @Override
                public Class<?> getColumnClass(int columnIndex)
                {
                    return columnClasses[columnIndex];
                }
            };
            AnchoColumna ac = new AnchoColumna(_tabla,colReadOnly);
//          OcultarColumnas oc = new OcultarColumnas(_tabla,0);
            JScrollPane scroll = new JScrollPane(_tabla);
            _tabla.getTableHeader().setReorderingAllowed(false);
            panelTabla.setVisible(false);
            panelTabla.add(scroll);
            panelTabla.setVisible(true);
            panelTabla.repaint();
        }
        catch(Exception ex)
        {
            
        }
    }
    
     private void CargarTabla()
     {
        try
        {
            _modeloTabla.RemoveAllRows();
            ResultSet rs = MainMenu.conexion.EjecutarConsulta("Select tmp.idinscripcion, tmp.alumno, tmp.grado, tmp.monto, tmp.saldo "+
                        "from ( select i.idinscripcion, a.nombre Alumno, g.nombre Grado, sum(di.monto) Monto, sum(di.saldo) Saldo "+
                        "from inscripciones i inner join detalleinscripcion di on i.idinscripcion=di.idinscripcion "+
                        "inner join alumnos a on i.idalumno=a.idalumno inner join grados g on i.idgrado=g.idgrado "+
                        "where i.debaja is null group by (i.idinscripcion) ) as tmp where tmp.Monto=tmp.Saldo");
            while (rs.next())
            {
                Vector alumno = new Vector();
                alumno.addElement(rs.getInt("idinscripcion"));//0
                alumno.addElement(rs.getString("alumno"));//1
                alumno.addElement(rs.getString("grado"));//2
                alumno.addElement(rs.getDouble("monto"));//3
                _modeloTabla.addRow(alumno);
            }
        }
        catch(Exception ex)
        {
            
        }
        finally
        {
            MainMenu.conexion.CerrarConexion();
        }
    }
    
     
    private void LimpiarVariables()
    {
        _IdInscripcion=0;
        _total=0;
        _modeloTabla.RemoveAllRows();
   }
    
    private void Nuevo()
    {
        int answer=JOptionPane.showConfirmDialog(null, "Perdera los datos no guardados, \n ¿desea continuar?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(answer == JOptionPane.YES_OPTION)
        {
            LimpiarVariables();
        }
    }
    
    private void Guardar() throws SQLException 
    {
        try
        {
            int selectedRow = 0;
            selectedRow = _tabla.getSelectedRow();
            _IdInscripcion =(Integer)_tabla.getValueAt(selectedRow, 0);
            _total = (Double)_tabla.getValueAt(selectedRow, 3);
        }
        catch(Exception ex){}
        int answer=JOptionPane.showConfirmDialog(null, "¿Desea Eliminar la Inscripción?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(answer == JOptionPane.YES_OPTION)
        {
            Connection _conexion=null;
            try
            {
                if (_IdInscripcion !=0 && _total>0)
                {
                    int idmovCuenta=0;
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    _conexion = DriverManager.getConnection("jdbc:mysql://"+MainMenu.server+"/"+MainMenu.dataBase,MainMenu.user, MainMenu.password);
                    _conexion.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                    _conexion.setAutoCommit(false);//Inicia la transaccion
                    Statement st = _conexion.createStatement();
                    st.execute("update inscripciones set debaja=now() where idinscripcion="+_IdInscripcion);
                    st.execute("update detalleinscripcion set debaja=now() where idinscripcion="+_IdInscripcion);
                    /*inserta el movimiento de cuenta */
                    Statement stMovCuenta = _conexion.createStatement();
                    stMovCuenta.execute("insert into movcuenta(fecha,tipo,id,idusuario,observaciones) values(now(),4,"+_IdInscripcion+","+MainMenu.IdUsuario+",'Anulacion Inscripcion')",Statement.RETURN_GENERATED_KEYS);
                    ResultSet rsMovCuenta = stMovCuenta.getGeneratedKeys();
                    if(rsMovCuenta.next()) 
                        idmovCuenta = rsMovCuenta.getInt(1);
                    stMovCuenta.execute("insert into detallemovcuenta(idmovcuenta,idcuenta,debe,haber) values("+idmovCuenta+",41,"+_total+","+0+")");
                    stMovCuenta.execute("insert into detallemovcuenta(idmovcuenta,idcuenta,debe,haber) values("+idmovCuenta+",8,"+0+","+_total+")");
                    /*Actualizar el saldo de las 2 cuentas CAPITAL Y CUENTAS POR COBRAR */
                    st.execute("update cuentas set saldo = saldo - "+_total+" where idcuenta in (8,41)");
                    _conexion.commit();
                    JOptionPane.showMessageDialog(this, "Los datos se eliminaron correctamente","Información",JOptionPane.INFORMATION_MESSAGE);
                    LimpiarVariables();
                }
                else
                    JOptionPane.showMessageDialog(this, "Debe seleccionar una inscripcion a Eliminar \n y el monto debe ser mayor a cero","Error",JOptionPane.ERROR_MESSAGE);
            }
            catch(Exception ex)
            {
                if (_conexion != null) 
                    _conexion.rollback();
                JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
            }
            finally
            {
                if (_conexion != null && !_conexion.isClosed())
                {
                    _conexion.close();
                    _conexion=null;
                    System.gc();
                }
            }
        }
    }
    
    private boolean VerificarInscripcionExiste(int idalumno,java.sql.Date del,java.sql.Date al)
    {
        try
        {
            ResultSet rs=null;
            rs=MainMenu.conexion.EjecutarConsulta("select count(*) from inscripciones where idalumno="+idalumno+" and debaja is null and (('"+del+"' between del and al) or ('"+al+"' between del and al))");
            if(rs.next())
            {
                if(rs.getInt(1)>0)
                {
                    return true;
                }
            }
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
        }
        finally
        {
            MainMenu.conexion.CerrarConexion();
        }
        return false;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelTabla = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Eliminar Inscripcion");
        setToolTipText("");

        panelTabla.setLayout(new java.awt.CardLayout());

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/refresh24.png"))); // NOI18N
        btnNuevo.setText("Refrescar");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/delete24.png"))); // NOI18N
        btnGuardar.setText("Eliminar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(btnNuevo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(btnGuardar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(btnNuevo)
                .add(18, 18, 18)
                .add(btnGuardar)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap(826, Short.MAX_VALUE)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(panelTabla, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(panelTabla, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try
        {
            Guardar();
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        Nuevo();
    }//GEN-LAST:event_btnNuevoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel panelTabla;
    // End of variables declaration//GEN-END:variables
}
